/*
 * Copyright 2012-2014 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.jqd.framework.core.hessian.web.controller;

import java.util.HashMap;
import java.util.Map;

import com.jqd.framework.core.exception.WebControllerException;
import com.jqd.framework.core.hessian.model.ServiceRequest;
import com.jqd.framework.core.hessian.model.ServiceResponse;
import com.jqd.framework.util.Assert;

/**
 * 
 * controller层辅助工具类
 * 
 * @author liaozhicheng.cn@gmail.com
 * @date 2012-6-11
 * @since 1.0
 */
public class WebUtils {
	
	// private constructor
	private WebUtils() {
	}
	
	
	public static ServiceResponse doDispatch(ServiceRequest serviceRequest)
			throws WebControllerException {
		return doDispatch(serviceRequest, DispatchService.DEFAULT_DISPATCH_SERVICE_NAME);
	}
	
	
	public static ServiceResponse doDispatch(ServiceRequest serviceRequest, String serviceName)
			throws WebControllerException {
		
		Assert.notNull(serviceRequest, "Parameter 'serviceRequest' can not be null");
		Assert.hasText(serviceRequest.getRequestedActionID(),
				"Property 'REQUESTED_ACTION_ID' can not be null or empty");
		
		DispatchService dispatchService = DispatchServiceFactory.getDispatchService();
		return dispatchService.doDispatch(serviceRequest, serviceName);
	}
	
	
	public static Map<String, Object> getResponseModel(Map<String, Object> requestModel,
			final String serviceRequestID) throws WebControllerException {
		try {
			ServiceRequest serviceRequest = new ServiceRequest();
			
			requestModel = (requestModel != null) ? requestModel : new HashMap<String, Object>();
			serviceRequest.setParameters(requestModel);
			serviceRequest.setRequestedActionID(serviceRequestID);
			
			ServiceResponse serviceResponse = doDispatch(serviceRequest);
			requestModel = serviceResponse.getModel();
			return requestModel;
		}
		catch (Exception e) {
			throw new WebControllerException(e);
		}
	}
	
}
